﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace A2DFramework.Infrastructure.Mvc.Extentions
{
    public static class EnumExtentions
    {

        //枚举类型转换成字典类型。枚举类型扩展方法
        public static Dictionary<int, string> ToDictionary(this Enum @enum)
        {
            var type = @enum.GetType();
            return Enum.GetValues(type).Cast<int>().ToDictionary(e => e, e => Enum.GetName(type, e));
        }

        //上一种方法的非扩展方法实现
        public static Dictionary<int, string> ToDictionary<TEnum>() where TEnum : struct
        {
            return Enum.GetValues(typeof(TEnum)).Cast<int>().ToDictionary(e => e, e => Enum.GetName(typeof(TEnum), e));
        }


        //Usage: ToDictionary<Colors>()
        public static Dictionary<string, TEnum> ToStrDictionary<TEnum>() where TEnum : struct
        {
            return Enum.GetValues(typeof(TEnum)).Cast<TEnum>().ToDictionary(e => Enum.GetName(typeof(TEnum), e));
        }

        //Usage: ToSelectList<Colors>()
        public static SelectList ToSelectList<TEnum>(this HtmlHelper h) where TEnum : struct
        {
            return new SelectList(ToStrDictionary<TEnum>(), "Key", "Value");
        }



        //public static class ReflectionHelpers
        //属性声明
        public static string GetCustomDescription(object objEnum)
        {
            var fi = objEnum.GetType().GetField(objEnum.ToString());
            var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? attributes[0].Description : objEnum.ToString();
        }

        //扩展方法
        public static string Description(this Enum value)
        {
            return GetCustomDescription(value);
        }

        //扩展方法
        public static string EnumName(this Enum value)
        {
            var type = value.GetType();
            return Enum.GetName(type, value);
        }


    }
}
